Print and Output with Elisp
Table of Contents
1. message Function
Its signature is
(message FORMAT_STRING &rest ARGS)
;; for example:
(message "Name is %s" "Joe") ; => Name is Joe
It displays a message at the bottom of the screen, as well as into the *Messages* buffer.
2. insert Function
insert function inserts string to current buffer at cursor position.
It has signature
(insert &rest ARGS)
;; for example
(insert "something")
3. Print to Buffer
The print function has signature
(print OBJECT &optional TARGET)
The print function will print the Lisp object in Lisp syntax with a newline.
Tips. When writing a Elisp script that does batch processing, it’s recommended to print to own buffer, because the *Messages* buffer scrolls off.
;; EXAMPLE:
(setq xbuff (generate-new-buffer "*my output*"))
(print "something" xbuff) ; print to our custom buffer
(switch-to-buffer xbuff)
It also has sibling functions: prin1 function acts like print function but without newline; princ function outputs in more human-readable format, and without newline.
4. Print to Warnings Buffer
Use the warn function, print messages to *Warnings* buffer.
(warn FORMAT_STRING &rest ARGS)
;; EXAMPLE:
(warn "You got a problem: %s" "Incorrect input.")
5. Temporarily Specify a Buffer for Output
This feature is akin to with ... as ... feature in Python. It binds standard output to a specified buffer, evaluates the body, and then show that buffer. The buffer is cleared before getting printed to; print functions print to this buffer by default.
;; SYNTAX:
(with-output-to-temp-buffer BUFFER_NAME &rest BODY)
;; EXAMPLE:
(let ((xbuff (generate-new-buffer "*MY OUTPUT*")))
(with-output-to-temp-buffer xbuff
(print "ABC") ; This string is printed to xbuff
))